package com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.repository.HddcB5GeophysvyprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.repository.HddcB5GeophysvyprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.repository.entity.HddcB5GeophysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.service.HddcB5GeophysvyprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.viewobjects.HddcB5GeophysvyprojecttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.viewobjects.HddcB5GeophysvyprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyProjectTable.viewobjects.HddcB5GeophysvyprojecttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcB5GeophysvyprojecttableServiceImpl implements HddcB5GeophysvyprojecttableService {

    private final HddcB5GeophysvyprojecttableRepository hddcB5GeophysvyprojecttableRepository;
    private final HddcB5GeophysvyprojecttableNativeRepository hddcB5GeophysvyprojecttableNativeRepository;
    private final GeophysicsExploreEngineeringExcelVerifyHandler geophysicsExploreEngineeringExcelVerifyHandler;

    @Autowired
    public HddcB5GeophysvyprojecttableServiceImpl(HddcB5GeophysvyprojecttableRepository hddcB5GeophysvyprojecttableRepository,
                                                  HddcB5GeophysvyprojecttableNativeRepository hddcB5GeophysvyprojecttableNativeRepository,
                                                  GeophysicsExploreEngineeringExcelVerifyHandler geophysicsExploreEngineeringExcelVerifyHandler) {
        this.hddcB5GeophysvyprojecttableRepository = hddcB5GeophysvyprojecttableRepository;
        this.hddcB5GeophysvyprojecttableNativeRepository = hddcB5GeophysvyprojecttableNativeRepository;
        this.geophysicsExploreEngineeringExcelVerifyHandler = geophysicsExploreEngineeringExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB5Geophysvyprojecttables(HddcB5GeophysvyprojecttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB5GeophysvyprojecttablePageVO> hddcB5GeophysvyprojecttablePage = this.hddcB5GeophysvyprojecttableNativeRepository.queryHddcB5Geophysvyprojecttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB5GeophysvyprojecttablePage);
    }


    @Override
    public HddcB5GeophysvyprojecttableEntity getHddcB5Geophysvyprojecttable(String id) {
        return this.hddcB5GeophysvyprojecttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB5GeophysvyprojecttableEntity saveHddcB5Geophysvyprojecttable(HddcB5GeophysvyprojecttableEntity hddcB5Geophysvyprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB5Geophysvyprojecttable.setUuid(uuid);
        hddcB5Geophysvyprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB5Geophysvyprojecttable.setCreateTime(now);
        hddcB5Geophysvyprojecttable.setUpdateTime(now);
        hddcB5Geophysvyprojecttable.setIsValid(PlatformConstants.Y);
        hddcB5Geophysvyprojecttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB5Geophysvyprojecttable.setExtends10(PlatformConstants.Y);
        this.hddcB5GeophysvyprojecttableRepository.save(hddcB5Geophysvyprojecttable);
        return hddcB5Geophysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB5GeophysvyprojecttableEntity updateHddcB5Geophysvyprojecttable(HddcB5GeophysvyprojecttableEntity hddcB5Geophysvyprojecttable) {
        HddcB5GeophysvyprojecttableEntity entity = hddcB5GeophysvyprojecttableRepository.findById(hddcB5Geophysvyprojecttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB5Geophysvyprojecttable);
        hddcB5Geophysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB5Geophysvyprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB5GeophysvyprojecttableRepository.save(hddcB5Geophysvyprojecttable);
        return hddcB5Geophysvyprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB5Geophysvyprojecttables(List<String> ids) {
        List<HddcB5GeophysvyprojecttableEntity> hddcB5GeophysvyprojecttableList = this.hddcB5GeophysvyprojecttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB5GeophysvyprojecttableList) && hddcB5GeophysvyprojecttableList.size() > 0) {
            for(HddcB5GeophysvyprojecttableEntity hddcB5Geophysvyprojecttable : hddcB5GeophysvyprojecttableList) {
//                this.hddcB5GeophysvyprojecttableRepository.delete(hddcB5Geophysvyprojecttable);
                hddcB5Geophysvyprojecttable.setIsValid("0");
                hddcB5Geophysvyprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB5Geophysvyprojecttable.setUpdateTime(new Date());
                this.hddcB5GeophysvyprojecttableRepository.save(hddcB5Geophysvyprojecttable);

            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB5GeophysvyprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB5GeophysvyprojecttableEntity> yhDisasterEntities = hddcB5GeophysvyprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB5GeophysvyprojecttableVO> list=new ArrayList<>();
        for (HddcB5GeophysvyprojecttableEntity entity:yhDisasterEntities) {
            HddcB5GeophysvyprojecttableVO yhDisasterVO=new HddcB5GeophysvyprojecttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球物理探测工程表", "地球物理探测工程表",
                HddcB5GeophysvyprojecttableVO.class, "地球物理探测工程表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(geophysicsExploreEngineeringExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB5GeophysvyprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB5GeophysvyprojecttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB5GeophysvyprojecttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB5GeophysvyprojecttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB5GeophysvyprojecttableVO> list) {
        for (HddcB5GeophysvyprojecttableVO hddcB5GeophysvyprojecttableVO : list) {
            HddcB5GeophysvyprojecttableEntity yhDisasterEntity = new HddcB5GeophysvyprojecttableEntity();
            BeanUtils.copyProperties(hddcB5GeophysvyprojecttableVO, yhDisasterEntity);
            saveHddcB5Geophysvyprojecttable(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB5GeophysvyprojecttableEntity> hddcDataList = this.hddcB5GeophysvyprojecttableRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB5GeophysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB5GeophysvyprojecttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB5GeophysvyprojecttableEntity> hddcDataList = this.hddcB5GeophysvyprojecttableRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB5GeophysvyprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB5GeophysvyprojecttableRepository.save(entity);
            }
        }
    }

}
